package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.commen.BaseContext;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    @Autowired
    private IDishFlavorService dishFlavorService;


    @Transactional
    public void saveWithFlavor(DishDto dishDto){
        log.info(dishDto.toString());
        this.save(dishDto);
        Long id = dishDto.getId();
        log.info(id.toString());
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(new Consumer<DishFlavor>() {
            @Override
            public void accept(DishFlavor dishFlavor) {
                dishFlavor.setDishId(id);
            }
        });
//        flavors = flavors.stream().map(item -> {
//            item.setDishId(id);
//            return item;
//        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto, HttpServletRequest request) {
        Long empID = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empID);
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);
        List<DishFlavor> flavors = dishDto.getFlavors();
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void editStatus(Integer status, List<Long> ids) {
        LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
        luw.set(Dish::getStatus, status).in(Dish::getId, ids);
        this.update(luw);
    }
}
